//
//  SLVerifyCodeVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/10.
//

#import "SLVerifyCodeVC.h"
#import "SLSetPswdVC.h"
@interface SLVerifyCodeVC ()<UITextFieldDelegate>

@end

@implementation SLVerifyCodeVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
}

-(void)setUpSubViews{
    _sureBtn.btnStyle = 1;
    [_sureBtn setTitle:kLocalString(@"Submit code") forState:UIControlStateNormal];
    _topTipLbl.text = kLocalString(@"Verify account");
    NSString *msg = kLocalString(@"The 5-digit verify code has been sent to <1>");
    NSString *email = _userModel.email;
    if (_pushEmail.length > 0) {
        email = _pushEmail;
    }
    msg = [msg stringByReplacingOccurrencesOfString:@"<1>" withString:email];
    _tipLbl.text = msg;
    
    [_resendBtn setLineTextWith:kLocalString(@"Resend code")];
    [self setBgViewLayout:_bView1];
    [self setBgViewLayout:_bView2];
    [self setBgViewLayout:_bView3];
    [self setBgViewLayout:_bView4];
    [self setBgViewLayout:_bView5];
    _tf.font = kFontMedium(30);
    _tf.tintColor = [UIColor clearColor];
    _tf.textColor = KClearColor;
    [_tf addTarget:self action:@selector(textFieldChangeAction:) forControlEvents:UIControlEventEditingChanged];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self->_tf becomeFirstResponder];
    });
    _tf.keyboardType = UIKeyboardTypeNumberPad;
    
    _tf.delegate = self;
    if (_style == 1) {
        self.title = kLocalString(@"Create account");
    }else if (_style == 2){
        self.title = kLocalString(@"Forgot Password");
    }else if (_style == 3){
        self.title = kLocalString(@"Change notification Email");
    }
}

-(void)textFieldChangeAction:(UITextField *)tf{
    if (tf.text.length > 5) {
        tf.text = [tf.text substringWithRange:NSMakeRange(0, 5)];
    }
    UILabel *label1 = [_bView1 viewWithTag:1];
    UILabel *label2 = [_bView2 viewWithTag:1];
    UILabel *label3 = [_bView3 viewWithTag:1];
    UILabel *label4 = [_bView4 viewWithTag:1];
    UILabel *label5 = [_bView5 viewWithTag:1];
    _bView1.layer.borderColor = kHexColor(@"#707070").CGColor;
    _bView2.layer.borderColor = kHexColor(@"#707070").CGColor;
    _bView3.layer.borderColor = kHexColor(@"#707070").CGColor;
    _bView4.layer.borderColor = kHexColor(@"#707070").CGColor;
    _bView5.layer.borderColor = kHexColor(@"#707070").CGColor;
    label1.text = @"";
    label2.text = @"";
    label3.text = @"";
    label4.text = @"";
    label5.text = @"";
    
    //这里修改字符间距
    if (tf.text.length >= 1) {
        NSString *str = [tf.text substringWithRange:NSMakeRange(0, 1)];
        label1.text = str;
        _bView1.layer.borderColor = KColor_O.CGColor;
    }
    
    if (tf.text.length >= 2) {
        NSString *str = [tf.text substringWithRange:NSMakeRange(1, 1)];
        label2.text = str;
        _bView2.layer.borderColor = KColor_O.CGColor;
    }
    if (tf.text.length >= 3) {
        NSString *str = [tf.text substringWithRange:NSMakeRange(2, 1)];
        label3.text = str;
        _bView3.layer.borderColor = KColor_O.CGColor;
    }
    if (tf.text.length >= 4) {
        NSString *str = [tf.text substringWithRange:NSMakeRange(3, 1)];
        label4.text = str;
        _bView4.layer.borderColor = KColor_O.CGColor;
    }
    if (tf.text.length >= 5) {
        NSString *str = [tf.text substringWithRange:NSMakeRange(4, 1)];
        label5.text = str;
        _bView5.layer.borderColor = KColor_O.CGColor;
    }
}

-(void)setBgViewLayout:(UIView *)bView{
    bView.layer.cornerRadius = 20;
    bView.layer.masksToBounds = YES;
    bView.layer.borderColor = kHexColor(@"#707070").CGColor;
    bView.layer.borderWidth = 1;
    
    UILabel *label = [[UILabel alloc] init];
    label.font = kFontMedium(30);
    label.textColor = KWhiteColor_text;
    label.textAlignment = NSTextAlignmentCenter;
    label.tag = 1;
    [bView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
}

- (IBAction)sureAction:(id)sender {
    if (_tf.text.length != 5) {
        kShowToast(@"Please enter the verification code");
        return;
    }
    NSString *url;
    NSDictionary *params;
    kWeakSelf(self);
    //创建账号
    if (_style == 1) {
        url = @"/msl_user/register";
        params = @{@"nickName":_userModel.nickName,
                   @"email":_userModel.email,
                   @"password":_userModel.password,
                   @"verificationCode":_tf.text};
        [ZCTool showLoadingOnKeyWindow];
        [ZKHttpManager postWithPath:url params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            [self showSuccessViews:kLocalString(@"Register account Success!")];
            
        }];
    }else if(_style == 2){
        url = [NSString stringWithFormat:@"/msl_user/CheckMailCode/%@/%@",_userModel.email,_tf.text];
        [ZCTool showLoadingOnKeyWindow];
        [ZKHttpManager getWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            //修改密码
            SLSetPswdVC *vc = [[SLSetPswdVC alloc] init];
            vc.style = weakself.style;
            vc.userModel = weakself.userModel;
            vc.verificationCode = weakself.tf.text;
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }else if (_style == 3) {
        
        url = [NSString stringWithFormat:@"/msl_user/CheckMailCode/%@/%@",_pushEmail,_tf.text];
        [ZCTool showLoadingOnKeyWindow];
        [ZKHttpManager getWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            NSDictionary *params = @{@"pushEmail":weakself.pushEmail};
            [ZCTool showLoadingOnKeyWindow];
            [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [ZCTool hideLoadingOnKeyWindow];
                if (!isSuccessed) {
                    kShowToast(message);
                    return;
                }
                kCurClickDevice.isOpenPush = YES;
                kCurClickDevice.pushEmail = weakself.pushEmail;
                //修改密码
                if (self.changeEmailBlock) {
                    self.changeEmailBlock(weakself.pushEmail);
                }
                kNotifyRefreshDevcieList;
                UIViewController *vc = [UIViewController viewControllerWithClassName:@"SLDeviceSettingVC"];
                [self.navigationController popToViewController:vc animated:YES];
            }];
        }];
    }
}

-(void)loginAndPushHomeVc{
    NSDictionary *params = @{@"email":_userModel.email,
                             @"password":_userModel.password};
    [ZCTool showLoadingOnKeyWindow];
    [ZKHttpManager postWithPath:@"/msl_user/login" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        NSString *token = kSTRING(result[@"result"][@"token"]);
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
        KPostNotification(KNotificationLoginStateChange, @YES);
    }];
}

-(void)showSuccessViews:(NSString *)message{
    __weak SLSuccessAlertView *alert = [SLSuccessAlertView viewFromXIB];
    kWeakSelf(self);
    alert.contentLbl.text = message;
    [alert setBtnBlock:^(NSInteger btnIndex) {
        [alert removeFromSuperview];
        //直接登录到首页
        [self loginAndPushHomeVc];
    }];
    [kAppWindow addSubview:alert];
}

- (IBAction)resendActiton:(id)sender {
    
    kWeakSelf(self);
    [ZCTool showLoadingOnKeyWindow];
    NSString *email = _userModel.email;
    if (_style == 3) {
        email = _pushEmail;
    }
    NSString *url = [NSString stringWithFormat:@"/msl_user/sendMail/%@",email];
    [ZKHttpManager postWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        kShowToast(message);
    }];
}

@end
